package test.thread;

public class SerialNum {

    private static int nextSerialNum = 0;

    private static ThreadLocal serialNum = new ThreadLocal() {
        @Override
        protected synchronized Object initialValue() {
            return new Integer(nextSerialNum++);
        }
    };

    public static int get() {
        return ((Integer) serialNum.get()).intValue();
    }

    public static void main(String[] args) {

        SerialNum serialNum = new SerialNum();

        for (int i = 0 ; i < 5 ; i ++) {
            System.out.println("the index is: " + i);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("sub thread serial num:" + SerialNum.get());
                }
            }).start();
        }

        System.out.println("main thread serial num:" + SerialNum.get());

    }

}
